<?php

class dispatch
{
   private static $tpl_data     = array();
   private static $tpl_compiled = '';
   private static $_subject     = '';
   private static $_start       = '';

   public static $templates     = array();
   
   public static function buildHtml($id, $usedItems = array(), $temporary = TRUE)
   {
      if(!is_numeric($id)) return FALSE;
      
      $DB = database::getInstance();
      $DB->sql = 'SELECT * FROM `meccano_dispatch_tmpl` WHERE `id` = '. $id;
      $DB->DB_Query();
      if($DB->DB_GetRows())
      {
         self::$tpl_data    = $DB->DB_FetchFlat();
         $template          = self::$tpl_data['template'];
         $dispatch_settings = config::read('settings', 'dispatch');
         
         $p = strpos($template, '%article%');
         $t = strpos($template, '%/article%');
         if($p === FALSE || $t === FALSE) return $template;
         
         $tmp = array();
         $tmp['before']  = substr($template, 0, $p);
         $tmp['after']   = substr($template, ($t+10));
         $tmp['article'] = substr($template, ($p+9), ($t-$p-9));
         $template       = $tmp;
         
         $_ARTICLES = new articles();
         $_ARTICLES->setOrder('`sdate` DESC');
         paginator::setItemsOnPage(15);
         
         $set = array();
         $set['active'] = array('type' => 'exact', 'value' => 1);
         $set['sdate']  = array('type' => 'more', 'value' => date('Y-m-d H:i:s', config::read('sent', 'dispatch')));
         
         if(!empty($usedItems['article']))
         {
            $usedItems['article'] = array_filter((array)$usedItems['article'], 'is_numeric');
            if(!empty($usedItems['article'])) $set['id'] = array('type' => 'exact', 'value' => $usedItems['article']);
         }
         
         if(!empty($dispatch_settings['categories']))
         {
            $set['cat']    = array('type' => 'exact', 'value' => array());
            foreach($dispatch_settings['categories'] AS $v)
            {
               $set['cat']['value'][] = $v;
               $v = tree_static::getChildrenId($v);
               if(is_array($v)) $set['cat']['value'] = array_merge($set['cat']['value'], $v);
            }
         }
         
         $articles = $_ARTICLES->getArticles(array('field' => $set));
         
         $output = $template['before'];
         if(!empty($articles))
         {
            self::$templates['article'] = $template['article'];
            $SMARTY = new MeccanoSmarty(array());
            $SMARTY->register_resource('ram', array('ram_get_template', 'ram_get_timestamp', 'ram_get_secure', 'ram_get_trusted'));

            foreach($articles AS $a)
            {
               $SMARTY->assign('article', $a);
               
               if($temporary)
               {
                  $output .= '<div style="position:relative;">';
                  $output .= '<input type="hidden" name="f[article][]" value="'. $a->id .'" />';
                  $output .= '<a href="" class="a_icon i_delete" style="display:block; position: absolute; left: -50px; top: 10px;"></a>';
                  $output .= $SMARTY->fetch("ram:article");
                  $output .= '</div>';
               } else
               {
                  $output .= $SMARTY->fetch("ram:article");
               }
            }
         }
         $output .= $template['after'];
         
         self::$tpl_compiled = $output;
         return self::$tpl_compiled;
      }
      
      return FALSE;
   }
   
   
   public static function sendDispatch($subject = FALSE, $start = FALSE, $groups = array())
   {
      if(empty(self::$tpl_compiled) || empty(self::$tpl_data)) return false;
      $dispatchID = FALSE;
      
      self::$_subject = !empty($subject)              ? (string)$subject  : self::$tpl_data['title'];
      self::$_start   = is_numeric(strtotime($start)) ? strtotime($start) : time();
      if(!empty($groups)) $groups = array_filter($groups, 'is_numeric');
      if(empty($groups))  $groups = array(4);
      $set   = array();
      $set['g'] = array('gid' => $groups);
      $set['u'] = array('active' => 1);
      $_U    = users::getInstance();
      $users = $_U->getUsers($set, TRUE);
      
      $DB = database::getInstance();
      $DB->DB_QueryBuilder('INSERT INTO `meccano_dispatch` (`sdate`, `uid`, `subject`, `body`, `groups`, `emails`) 
         VALUES (
            "'. date("Y-m-d H:s:i", self::$_start) .'",
            '. session::user()->id .',
            "%s",
            "%s",
            "'. join(',', $groups) .'",
            0
         )',
         array(self::$_subject, self::$tpl_compiled));
      $DB->DB_Query();
      
      $dispatchID     = $DB->DB_LastID();
      $dispatchEmails = 0;
      $firstGoes      = FALSE;
      
      email::setCategory('dispatch');
      email::setSign($dispatchID);
      email::setStartTime(self::$_start);
      email::setSender(self::$tpl_data['from_email'], self::$tpl_data['from_name']);
      
      foreach($users AS $u)
      {
         $e = $u->email;
         if(!empty($e))
         {
            $unsubscribeID = 'http://'. config::read('domain', 'file') . tree_static::getNode(8)->url . $u->id .'/'. self::getUserHash($u) .'/unsubscribe';
            
            $message = str_replace(
                    array('%username%', '%unsubscribe%'), 
                    array($u->name, $unsubscribeID), 
                    self::$tpl_compiled);
            
            $r = email::queue($e, self::$_subject, $message, array(
               'recipient_name' => $u->name
            ));
            if($r)
            {
               $dispatchEmails++;
               if(!$firstGoes)
               {
                  config::write('sent', 'dispatch', time());
                  $firstGoes = TRUE;
               }
            }
         }
      }
      
      email::reset();
      
      $DB->sql = 'UPDATE `meccano_dispatch` SET `emails` = '. $dispatchEmails .' WHERE `id` = '. $dispatchID;
      $DB->DB_Query();
      
      return $dispatchID;
   }
   
   
   public static function getList()
   {
      $_U = users::getInstance();
      $DB = database::getInstance();
      # GET DISPATCH LIST
      $usersGroups = $_U->getGroups();
      
      $DB->sql = 'SELECT * FROM `meccano_dispatch` ORDER BY `sdate` DESC LIMIT 0, 30';
      $dispatchList = $DB->DB_Fetch();
      if(!empty($dispatchList))
      {
         $dispatchUsers  = array();
         foreach($dispatchList AS $k=>$v)
         {
            $dispatchUsers[] = $v['uid'];
            $tmp = explode(',', $v['groups']);
            $dispatchList[$k]['groups'] = array();
            for($i=0; $i<sizeof($tmp); $i++)
            {
               $dispatchList[$k]['groups'][] = $usersGroups[$tmp[$i]]['group'];
            }
         }
         
         $dispatchUsers  = array_unique($dispatchUsers);
         $set   = array();
         $set['u'] = array('id' => $dispatchUsers);
         $users = $_U->getUsers($set, TRUE);
         
         foreach($dispatchList AS $k=>$v)
         {
            $dispatchList[$k]['user'] = '['. $users[$v['uid']]->login .'] '. $users[$v['uid']]->name .' '. $users[$v['uid']]->surname;
         }
      }
      
      return $dispatchList;
   }
   
   public static function getTemplate()
   {
      return self::$tpl_data;
   }
   
   public static function getUserHash($userObject)
   {
      return md5(config::read('salt', 'file') . $userObject->login);
   }
}